package org.finesys.common.redis.core.mq.client;

import lombok.AllArgsConstructor;
import lombok.Getter;
import org.finesys.commom.jackson.util.JacksonUtil;
import org.finesys.common.redis.core.mq.interceptor.RedisMessageInterceptor;
import org.finesys.common.redis.core.mq.message.AbstractRedisMessage;
import org.finesys.common.redis.core.mq.pubsub.AbstractPubSubMessage;
import org.finesys.common.redis.core.mq.stream.AbstractStreamMessage;
import org.springframework.data.redis.connection.stream.ObjectRecord;
import org.springframework.data.redis.connection.stream.RecordId;
import org.springframework.data.redis.connection.stream.StreamRecords;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * redis消息队列操作类
 */
@Getter
@AllArgsConstructor
public class RedisMQTemplate {

	private final RedisTemplate<String, ?> redisTemplate;

	/**
	 * 拦截器数组
	 */
	private final List<RedisMessageInterceptor> interceptors = new ArrayList<>();

	/**
	 * 基于Stream
	 * @param message 消息
	 * @return 消息记录的编号对象
	 */
	public <T extends AbstractStreamMessage> RecordId send(T message) {

		try {
			// 发送消息前拦截器处理
			sendMessageBefore(message);
			// 构建 ObjectRecord
			ObjectRecord<String, String> record = StreamRecords.newRecord()
				.ofObject(JacksonUtil.toJsonString(message))
				.withStreamKey(message.getStreamKey());
			// 发送消息
			return redisTemplate.opsForStream().add(record);
		}
		finally {
			// 消息发送后拦截器处理
			sendMessageAfter(message);
		}
	}

	/**
	 * 基于发布订阅
	 */
	public <T extends AbstractPubSubMessage> void send(T message) {
		try {
			// 发送消息前拦截器处理
			sendMessageBefore(message);
			// 发送消息
			redisTemplate.convertAndSend(message.getTopic(), JacksonUtil.toJsonString(message));
		}
		finally {
			// 消息发送后拦截器处理
			sendMessageAfter(message);
		}

	}

	/**
	 * 添加拦截器
	 */
	public void addInterceptor(RedisMessageInterceptor interceptor) {
		interceptors.add(interceptor);
	}

	private <T extends AbstractStreamMessage> void sendMessageAfter(AbstractRedisMessage message) {
		for (int i = interceptors.size() - 1; i >= 0; i--) {
			interceptors.get(i).sendMessageAfter(message);
		}
	}

	private <T extends AbstractStreamMessage> void sendMessageBefore(AbstractRedisMessage message) {
		interceptors.forEach(redisMessageInterceptor -> redisMessageInterceptor.sendMessageBefore(message));

	}

}
